<template>
  <div class="personal-info">
    <h2>个人信息详情</h2>

    <!-- 加载状态 -->
    <div class="loading" v-if="globalStore.isLoading">查询中...</div>

    <!-- 错误提示 -->
    <div class="error-alert" v-if="globalStore.errorMsg">
      {{ globalStore.errorMsg }}
    </div>

    <div class="actions" style="max-width:800px;margin: 0 auto 16px; text-align:right;">
      <el-button type="primary" size="small" @click="toggleEdit" v-if="!editing">编辑信息</el-button>
      <el-button size="small" @click="toggleEdit" v-else>取消</el-button>
    </div>

    <!-- 编辑表单 -->
    <el-card class="info-card" v-if="editing">
      <el-form :model="employeeForm" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="员工ID">
          <span>{{ employeeForm.empId || '-' }}</span>
        </el-form-item>

        <el-form-item label="姓名" prop="empName">
          <el-input v-model="employeeForm.empName" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="employeeForm.gender" placeholder="请选择">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
            <el-option label="其他" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="部门ID" prop="deptId">
          <el-input v-model.number="employeeForm.deptId" />
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-input v-model="employeeForm.position" />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="employeeForm.phone" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email" />
        </el-form-item>

        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker v-model="employeeForm.hireDate" type="date" placeholder="选择日期" style="width:100%" />
        </el-form-item>

        <el-form-item label="离职日期" prop="resignDate">
          <el-date-picker v-model="employeeForm.resignDate" type="date" placeholder="选择日期" style="width:100%" />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="employeeForm.address" />
        </el-form-item>

        <div style="text-align:center;margin-top:18px;">
          <el-button type="primary" :loading="saving" @click="saveInfo">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 个人信息卡片（查询成功后展示） -->
    <div class="info-card" v-else-if="employeeInfo.empId">
      <div class="info-item">
        <label>员工ID：</label>
        <span>{{ employeeInfo.empId }}</span>
      </div>
      <div class="info-item">
        <label>姓名：</label>
        <span>{{ employeeInfo.empName }}</span>
      </div>
      <div class="info-item">
        <label>性别：</label>
        <span>{{ employeeInfo.gender }}</span>
      </div>
      <div class="info-item">
        <label>部门ID：</label>
        <span>{{ employeeInfo.deptId }}</span>
      </div>
      <div class="info-item">
        <label>职位：</label>
        <span>{{ employeeInfo.position }}</span>
      </div>
      <div class="info-item">
        <label>入职日期：</label>
        <span>{{ employeeInfo.hireDate }}</span>
      </div>
      <div class="info-item">
        <label>离职日期：</label>
        <span>{{ employeeInfo.resignDate }}</span>
      </div>
      <div class="info-item">
        <label>联系电话：</label>
        <span>{{ employeeInfo.phone }}</span>
      </div>
      <div class="info-item">
        <label>邮箱：</label>
        <span>{{ employeeInfo.email }}</span>
      </div>
      <div class="info-item">
        <label>联系地址：</label>
        <span>{{ employeeInfo.address }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { useGlobalStore, axios } from "@/stores/index";
import { useAuthStore } from "@/stores/auth";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  setup() {
    const globalStore = useGlobalStore();
    const authStore = useAuthStore();
    const formRef = ref(null);
    const employeeInfo = ref({}); // 展示用
    const employeeForm = ref({
      empId: null,
      loginId: null,
      empName: "",
      gender: "",
      deptId: null,
      position: "",
      phone: "",
      email: "",
      hireDate: "",
      resignDate: "",
      address: "",
    });

    const editing = ref(false);
    const saving = ref(false);

    const rules = {
      empName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      phone: [{ required: false }],
      email: [{ type: "email", message: "请输入正确的邮箱", trigger: "blur" }],
    };

    // 将后端返回的数据映射到展示模型和表单
    const mapResultToModel = (res) => {
      // res 可能已经是 data（由 axios interceptor 返回），也可能是对象
      const src = res || {};
      const mapped = {
        empId: src.empId ?? src.empID ?? src.id ?? null,
        loginId: src.loginId ?? null,
        empName: src.empName ?? src.empName ?? src.username ?? "",
        gender: src.gender ?? "",
        deptId: src.deptId ?? src.deptId ?? null,
        position: src.position ?? "",
        phone: src.phone ?? "",
        email: src.email ?? "",
        hireDate: src.hireDate ? formatDateString(src.hireDate) : "",
        resignDate: src.resignDate ? formatDateString(src.resignDate) : "",
        address: src.address ?? "",
      };
      employeeInfo.value = { ...mapped };
      employeeForm.value = { ...mapped };
    };

    const formatDateString = (val) => {
      if (!val) return "";
      // 如果已经是 yyyy-MM-dd，直接返回；否则尝试 new Date
      if (typeof val === "string" && val.length <= 10 && val.includes("-")) return val;
      const d = new Date(val);
      if (isNaN(d)) return "";
      const yyyy = d.getFullYear();
      const mm = String(d.getMonth() + 1).padStart(2, "0");
      const dd = String(d.getDate()).padStart(2, "0");
      return `${yyyy}-${mm}-${dd}`;
    };

    // 获取 empId（通过 loginId），然后获取员工详情
    const fetchPersonalInfo = async () => {
      try {
        globalStore.setLoading(true);
        const loginId = authStore.currentLoginId || localStorage.getItem("currentLoginId") || localStorage.getItem("loginId");
        if (!loginId) {
          throw new Error("未找到 loginId，请先登录");
        }

        // 第一步：通过 loginId 获取 empId
        const empIdData = await axios.get("/user/getEmpId", { params: { loginId } });
        // axios interceptor 返回 data，可能为数字或对象
        let empId = empIdData;
        if (empId && typeof empId === "object") {
          empId = empId.empId ?? empId.id ?? empId.data ?? null;
        }

        if (!empId) {
          throw new Error("未能获取 empId");
        }

        // 第二步：使用 empId 获取员工详情
        // 假设后端有 GET /userManage/{empId} 返回 employee 对象
        const detail = await axios.get(`/userManage/${empId}`);
        mapResultToModel(detail);
      } catch (err) {
        console.error("查询个人信息失败：", err);
        globalStore.setErrorMsg(err.message || "查询失败");
      } finally {
        globalStore.setLoading(false);
      }
    };

    onMounted(() => {
      fetchPersonalInfo();
    });

    const toggleEdit = () => {
      editing.value = !editing.value;
      if (editing.value) {
        // 进入编辑状态时确保表单已被填充
        employeeForm.value = { ...employeeInfo.value };
      }
    };

    const resetForm = () => {
      if (formRef.value) formRef.value.resetFields();
      // 恢复为最新的展示数据
      employeeForm.value = { ...employeeInfo.value };
    };

    // 保存修改（PUT /userManage），请求体参考接口示例
    const saveInfo = async () => {
      try {
        await formRef.value.validate();
      } catch (e) {
        ElMessage.warning("请先修正表单错误");
        return;
      }

      saving.value = true;
      try {
        const payload = {
          empId: employeeForm.value.empId ?? 0,
          loginId: employeeForm.value.loginId ?? 0,
          empName: employeeForm.value.empName || "",
          gender: employeeForm.value.gender || "",
          deptId: employeeForm.value.deptId ?? 0,
          position: employeeForm.value.position || "",
          phone: employeeForm.value.phone || "",
          email: employeeForm.value.email || "",
          hireDate: employeeForm.value.hireDate ? new Date(employeeForm.value.hireDate).toISOString() : "",
          resignDate: employeeForm.value.resignDate ? new Date(employeeForm.value.resignDate).toISOString() : "",
          address: employeeForm.value.address || "",
          updateTime: new Date().toISOString(),
        };

        // PUT 提交
        await axios.put("/userManage", payload);

        ElMessage.success("更新成功");
        // 更新展示数据并退出编辑
        employeeInfo.value = { ...employeeForm.value };
        editing.value = false;
      } catch (err) {
        console.error("保存失败：", err);
        if (err.response?.status === 401) {
          ElMessageBox.confirm("登录已过期，请重新登录", "提示", {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            localStorage.removeItem("token");
            localStorage.removeItem("isLogin");
            window.location.href = "/login";
          });
        } else {
          ElMessage.error(err.response?.data?.message || err.message || "更新失败");
        }
      } finally {
        saving.value = false;
      }
    };

    return {
      globalStore,
      employeeInfo,
      employeeForm,
      fetchPersonalInfo,
      editing,
      toggleEdit,
      saveInfo,
      resetForm,
      formRef,
      rules,
      saving,
    };
  },
};
</script>

<style scoped>
.personal-info {
  padding: 20px;
}
h2 {
  color: #1f2937;
  margin-bottom: 20px;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 10px;
}
.loading {
  text-align: center;
  padding: 40px;
  color: #3b82f6;
}
.error-alert {
  max-width: 800px;
  margin: 0 auto 20px;
  padding: 12px;
  background: #fee2e2;
  color: #dc2626;
  border-radius: 4px;
}
.info-card {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
.info-item {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
}
.info-item label {
  width: 120px;
  font-weight: 500;
  color: #4b5563;
}
.info-item span {
  color: #1f2937;
  flex: 1;
}
.info-item:last-child {
  margin-bottom: 0;
}
</style>
